package com.wawu.common.utils.SQLBuilder;

import java.util.Map;

//TODO 待优化：加上反引号``,去避免关键字冲突
public class UpdateSQLBuilder extends BaseSQLBuilder {

    private boolean hasSetClause = false;

    public UpdateSQLBuilder(String tableName) {
        super("UPDATE " + tableName);
    }

    /**
     * 添加更新字段和值到 SET 子句（实时拼接到 sql）
     */
    public UpdateSQLBuilder setField(String fieldName, Object value) {
        if (fieldName != null && value != null) {
            if (!hasSetClause) {
                sql.append(" SET ");
                hasSetClause = true;
            } else {
                sql.append(", ");
            }
            sql.append(fieldName).append(" = ?");
            params.add(value);
        }
        return this;
    }

    /**
     * 添加多个更新字段和值
     */
    public UpdateSQLBuilder setFields(Map<String, Object> fields) {
        if (fields != null && !fields.isEmpty()) {
            fields.forEach(this::setField);
        }
        return this;
    }

    /**
     * 添加动态条件到 WHERE 子句
     */
    @Override
    public UpdateSQLBuilder addDynamicCondition(String fieldName, String operator, Object value) {
        super.addDynamicCondition(fieldName, operator, value);
        return this;
    }

    /**
     * 获取最终 SQL
     */
    @Override
    public String getSQL() {
        if (!hasSetClause) {
            throw new IllegalStateException("No fields specified for update. Please use setField() or setFields().");
        }
        // 调用父类的 getSQL 方法，完成 WHERE 子句拼接
        return super.getSQL();
    }
}